package com.zadetk.helpyou.activities;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zadetk.helpyou.R;
import com.zadetk.helpyou.base.AbsActivity;
import com.zadetk.helpyou.bean.InfoItemBean;
import com.zadetk.helpyou.bean.UserInfoBean;
import com.zadetk.helpyou.net.BaseObserver;
import com.zadetk.helpyou.net.BaseResponse;
import com.zadetk.helpyou.net.NetTool;
import com.zadetk.helpyou.other.Const;
import com.zadetk.helpyou.other.UserInfoManger;
import com.zadetk.helpyou.utils.LogUtil;
import com.zadetk.helpyou.utils.ToastUtil;
import com.zadetk.helpyou.view.dialog.BaseNiceDialog;
import com.zadetk.helpyou.view.dialog.NiceDialog;
import com.zadetk.helpyou.view.dialog.ViewConvertListener;
import com.zadetk.helpyou.view.dialog.ViewHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.MultipartBody;

/**
 * 4-1完善信息页面
 */
public class FullInfoActivity extends AbsActivity implements View.OnClickListener, BaseObserver.DialogHelper {

    private TextView rightTv;
    private ImageView ivChooseImg;
    private TextView tvNickname;
    private TextView tvSex;
    private TextView tvPhonenumber;
    private LinearLayout llAddress;
    private LinearLayout llSelfCredentials;
    private TextView tvCompanyname;
    private TextView tvCompanyphonenumber;
    private LinearLayout llCompanyAddress;
    private LinearLayout llCompanyCredentials;
    private TextView tvAddress, tvIdcard, tvCompaneyAddrss, tvCompaneyIdcard;
    private UserInfoBean userInfoBean;

    @Override
    public int setView() {
        return R.layout.activity_full_info;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initViews();
        initLogic();
        requestData();
    }

    private void requestData() {
        if (UserInfoManger.isFetchUserInfo) {
            userInfoBean = UserInfoManger.userInfo;
            upDateView();
            return;
        }
        Map<String, Object> param = NetTool.newParams(this);
        NetTool.getApi().getUserInfo(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<UserInfoBean>>() {
                    @Override
                    public void onData(BaseResponse<UserInfoBean> value) {
                        if (value.getCode() == 0) {
                            UserInfoManger.merage(value.getData(), UserInfoManger.userInfo);
                            userInfoBean = UserInfoManger.userInfo;
                            upDateView();
                        } else {
                            ToastUtil.showToast("获取用户信息出错！");
                            userInfoBean = new UserInfoBean();
                        }
                    }
                });
    }

    private void upDateView() {
        if (!TextUtils.isEmpty(userInfoBean.getNickname())) {
            tvNickname.setText(userInfoBean.getNickname());
        }
        if (!TextUtils.isEmpty(userInfoBean.getAvatar())) {
            Glide.with(this).load(userInfoBean.getAvatar()).into(ivChooseImg);
        }
        if (userInfoBean.getUsersex() == 1) tvSex.setText("男");
        if (userInfoBean.getUsersex() == 2) tvSex.setText("女");
        if (!TextUtils.isEmpty(userInfoBean.getUserphone())) {
            tvPhonenumber.setText(userInfoBean.getUserphone());
        }
        if (!TextUtils.isEmpty(userInfoBean.getUseraddress())) {
            tvAddress.setText(userInfoBean.getAddress());
        }
        if (!TextUtils.isEmpty(userInfoBean.getCompanyname())) {
            tvCompanyname.setText(userInfoBean.getCompanyname());
        }
        if (!TextUtils.isEmpty(userInfoBean.getCompanyphone())) {
            tvCompanyphonenumber.setText(userInfoBean.getCompanyphone());
        }
        if (!TextUtils.isEmpty(userInfoBean.getCompanyaddress())) {
            tvCompaneyAddrss.setText(userInfoBean.getCompanyaddress());
        }

    }

    private void initLogic() {
        rightTv.setOnClickListener(this);
        llSelfCredentials.setOnClickListener(this);
        llCompanyCredentials.setOnClickListener(this);
        ivChooseImg.setOnClickListener(this);
        tvNickname.setOnClickListener(this);
        tvSex.setOnClickListener(this);
        tvPhonenumber.setOnClickListener(this);
        tvCompanyname.setOnClickListener(this);
        tvCompanyphonenumber.setOnClickListener(this);
    }

    private void initViews() {
        rightTv = mToolbar.findViewById(R.id.tv_righttext);
        rightTv.setVisibility(View.VISIBLE);
        ivChooseImg = (ImageView) findViewById(R.id.iv_choose_img);
        tvNickname = (TextView) findViewById(R.id.tv_nickname);
        tvSex = (TextView) findViewById(R.id.tv_sex);
        tvPhonenumber = (TextView) findViewById(R.id.tv_phonenumber);
        llAddress = (LinearLayout) findViewById(R.id.ll_address);
        llSelfCredentials = (LinearLayout) findViewById(R.id.ll_self_credentials);
        tvCompanyname = (TextView) findViewById(R.id.tv_companyname);
        tvCompanyphonenumber = (TextView) findViewById(R.id.tv_companyphonenumber);
        llCompanyAddress = (LinearLayout) findViewById(R.id.ll_company_address);
        llCompanyCredentials = (LinearLayout) findViewById(R.id.ll_company_credentials);
        tvAddress = findViewById(R.id.tv_address);
        tvCompaneyAddrss = findViewById(R.id.tv_companey_address);
        tvIdcard = findViewById(R.id.tv_idcard);
        tvCompaneyIdcard = findViewById(R.id.tv_companey_idcard);
        setTopTitle("完善信息");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_righttext:

                break;
            case R.id.ll_company_credentials:
                startActivity(new Intent(this, UpLoadCredentialActivity.class).putExtra("type", 2));
                break;
            case R.id.ll_self_credentials:
                startActivity(new Intent(this, UpLoadCredentialActivity.class).putExtra("type", 1));
                break;
            case R.id.iv_choose_img:
                performCodeWithPermission("需要相册权限！", new PermissionCallback() {
                    @Override
                    public void hasPermission() {
                        MultiImageSelector.create().showCamera(true).single().start(FullInfoActivity.this, 200);
                    }

                    @Override
                    public void noPermission() {

                    }
                }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA});
                break;
            case R.id.tv_nickname:
                showInputDialog(Const.TYPE_NAME);
                break;
            case R.id.tv_sex:
                showInputDialog(Const.TYPE_SEX);
                break;
            case R.id.tv_phonenumber:
                showInputDialog(Const.TYPE_PHONE);
                break;
            case R.id.tv_companyname:
                showInputDialog(Const.TYPE_COMPANY_NAME);
                break;
            case R.id.tv_companyphonenumber:
                showInputDialog(Const.TYPE_COMPANEY_PHONE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 200) {
            ArrayList<String> list = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
            LogUtil.d(list.get(0));
            ToastUtil.showToast(list.get(0));
            File file = new File(list.get(0));
            changeInfoRequest(Const.TYPE_AVATOR, file);
        }
    }

    private void showInputDialog(final String type) {
        final NiceDialog tempDialog = NiceDialog.init();

        tempDialog.setLayoutId(R.layout.commit_layout)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        holder.setText(R.id.tv_title, type);
                        final EditText editText = (EditText) holder.getView(R.id.edit_input);
                        editText.post(new Runnable() {
                            @Override
                            public void run() {
                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.showSoftInput(editText, 0);
                            }
                        });
                        holder.setOnClickListener(R.id.tv_cancel_edit, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                tempDialog.dismiss();
                            }
                        });
                        holder.setOnClickListener(R.id.tv_confirm_edit, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                String input = editText.getText().toString();
                                if (TextUtils.isEmpty(input)) {
                                    ToastUtil.showToast("输入点什么再确定吧！");
                                } else {
                                    changeInfoRequest(type, input);
                                    tempDialog.dismiss();
                                }
                            }
                        });
                    }
                })
                .setOutCancel(false)
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    private void changeInfoRequest(String key, String value) {
        Map<String, Object> param = NetTool.newParams(this);
        param.put("key", key);
        param.put("value", value);
        NetTool.getApi().saveUserInfo(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<InfoItemBean>>() {
                    @Override
                    public void onData(BaseResponse<InfoItemBean> value) {
                        if (value.getCode() == 0) {
                            switch (value.getData().getKey()) {
                                case Const.TYPE_NAME:
                                    tvNickname.setText(value.getData().getValue());
                                    userInfoBean.setNickname(value.getData().getValue());
                                    break;
                                case Const.TYPE_SEX:
                                    tvSex.setText(value.getData().getValue());
                                    //userInfoBean.setUsersex(value.getData().getValue());
                                    break;
                                case Const.TYPE_PHONE:
                                    tvPhonenumber.setText(value.getData().getValue());
                                    userInfoBean.setUserphone(value.getData().getValue());
                                    break;
                                case Const.TYPE_AVATOR:
                                    Glide.with(FullInfoActivity.this).load(value.getData().getValue()).into(ivChooseImg);
                                    userInfoBean.setAvatar(value.getData().getValue());
                                    break;
                                case Const.TYPE_COMPANY_NAME:
                                    tvCompanyname.setText(value.getData().getValue());
                                    userInfoBean.setCompanyname(value.getData().getValue());
                                    break;
                                case Const.TYPE_COMPANEY_ADDRESS:
                                    tvAddress.setText(value.getData().getValue());
                                    userInfoBean.setAddress(value.getData().getValue());
                                    break;
                                case Const.TYPE_COMPANEY_PHONE:
                                    tvCompanyphonenumber.setText(value.getData().getValue());
                                    userInfoBean.setCompanyphone(value.getData().getValue());
                                    break;
                                case Const.TYPE_ADDRESS:
                                    tvCompaneyAddrss.setText(value.getData().getValue());
                                    userInfoBean.setCompanyaddress(value.getData().getValue());
                                    break;
                            }
                            ToastUtil.showToast("修改成功！");
                        } else {
                            ToastUtil.showToast(value.getMessage());
                        }
                    }
                });
    }

    private void changeInfoRequest(String key, File file) {
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addPart(NetTool.buildUploadMultipart(file, "value"))
                .addFormDataPart("key", key)
                .build();
        NetTool.getApi().saveUserInfo(multipartBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<InfoItemBean>>(this) {
                    @Override
                    public void onData(BaseResponse<InfoItemBean> value) {
                        if (value.getCode() == 0) {
                            switch (value.getData().getKey()) {
                                case Const.TYPE_AVATOR:
                                    Glide.with(FullInfoActivity.this).load(value.getData().getValue()).into(ivChooseImg);
                                    userInfoBean.setAvatar(value.getData().getValue());
                                    break;
                            }
                            ToastUtil.showToast("修改成功！");
                        } else {
                            ToastUtil.showToast(value.getMessage());
                        }
                    }
                });
    }

    @Override
    public void showLoadingProgress() {
        ToastUtil.showToast("正在上传！");
    }

    @Override
    public void dismissLoadingProgress() {

    }

    @Override
    public void showRetryView() {

    }
}
